package com.pc.admin.service.ipml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pc.admin.dto.UserDTO;
import com.pc.admin.entity.User;
import com.pc.admin.mapper.UserMapper;
import com.pc.admin.service.UserService;
import com.pc.admin.util.CommonResult;
import com.pc.admin.util.SMSUtils;
import com.pc.admin.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.builder.BuilderException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @author ZHANGJING
 * @date 2023/7/4 16:21
 */

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 移动端验证码登录 登陆校验
     *
     * @param dto 参数
     */
    @Override
    public CommonResult login(UserDTO dto) {
        // 1.从redis获取验证码
        String redisKey = "verification_code:" + dto.getPhone();
        String redisCode = redisTemplate.opsForValue().get(redisKey);
        log.info("从 Redis 获取验证码，key: {}, value: {}", redisKey, redisCode);
        // 2.根据用户输入的验证码与redis中的验证码进行对比
        if (StringUtils.isEmpty(dto.getCode()) || StringUtils.isEmpty(String.valueOf(redisCode))) {
            throw new BuilderException("请重新获取验证码");
        }
        if (!dto.getCode().equals(redisCode)) {
            throw new BuilderException("请输入正确验证码");
        }
        // 4.根据手机号查询用户表，判断用户是否存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, dto.getPhone());
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (user.getPhone() == null) {
            // 5.如果用户不存在，则自动注册用户
            user = new User();
            user.setPhone(dto.getPhone());
            user.setPassWord(dto.getPassWord());
            user.setStatus(1);
            userMapper.insert(user);
            log.info("插入用户信息成功");
        }
        log.info("<------用户{}登录成功了------>", dto.getPhone());
        return CommonResult.ok(user);
    }


    /**
     * 手机号码发送验证码
     *
     * @param phone
     */
    @Override
    public Integer sendMsg(String phone) throws Exception {
        //1生成验证码 通过工具类生成 验证码一般为4或6位
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("<------手机号为{}，验证码为{}------>", phone, code);
        //2发送验证码
        if (false) {//永不执行
            SMSUtils.sendMessage(phone, code.toString());
        }
        //3将验证码存入 Redis，设置过期时间（30分钟）
        String redisKey = "verification_code:" + phone;
        redisTemplate.opsForValue().set(redisKey, code.toString(), 30, TimeUnit.MINUTES);
        log.info("验证码已存入 Redis，key:{}, value:{}", redisKey, code.toString());
        log.info("发送验证码成功了");
        return code;
    }

    @Override
    public void logout(HttpSession httpSession) {
        httpSession.invalidate();
    }

}
